/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
//
/* eslint-disable */
import Blockly from '@scene/scene-blocks';

import { setProperty } from '@/utils/utils';
import '@/lib/block-theme-draw';
import './blockly'

let BlocksWidth = 300;
let MenuWidth = 100;
export let ToolboxWidth = MenuWidth + BlocksWidth;

export function setPreviewMode(status) {
  if (status) {
    BlocksWidth = 0;
    MenuWidth = 0;
  } else {
    BlocksWidth = 300;
    MenuWidth = 100;
  }
  ToolboxWidth = MenuWidth + BlocksWidth;
  // 设置全局css变量
  setProperty('--blocks-width', `${BlocksWidth}px`);
  setProperty('--menu-width', `${MenuWidth}px`);
  setProperty('--toolbox-width', `${BlocksWidth}px`);
  Blockly.VerticalFlyout.prototype.DEFAULT_WIDTH = BlocksWidth;
  // 配置左侧工具栏宽度
  Blockly.Toolbox.prototype.width = MenuWidth + BlocksWidth;
}

setPreviewMode(false);

// 控制下拉形状 true:下拉积木是圆形的 false: 下拉积木是方形的
export const ACCEPT_REPORTERS = true;



Blockly.ScratchMsgs.locales["zh-cn"].CATEGORY_CONTROL = '逻辑'
window.Blocklysss= Blockly
// https://developers.google.com/blockly/guides/configure/web/configuration_struct 配置文档
export const BLOCKS_DEFAULT_OPTIONS = {
  media: '../static/blocks-media/',
  // 设置积木分类猜到/积木弹出列表到右边
  toolboxPosition: 'start',
  horizontalLayout: false,
  rtl: false,
  zoom: {
    // 控件显示
    controls: false,
    // 积木缩放
    wheel: false,
    startScale: 0.675,
  },
  grid: {
    spacing: 40,
    length: 10,
    colour: '#cad6f7', // #00000000
  },
  colours: {
    // 积木工作区 背景色
    workspace: '#f0f2f5',
    // 积木弹出列表，背景色
    flyout: '#ffffff',
    // 积木分类菜单，背景色
    toolbox: '#ffffff',
    toolboxText: "#91949a",
    toolboxHover: "#333333",
    // 积木分类菜单，选中颜色
    toolboxSelected: '#EBF3FF',
    // 积木分类菜单，右侧选中颜色
    toolboxSelectedBorder: '#3569FD',
    // 滚动条颜色
    scrollbar: '#CECDCE',
    // hover状态下，滚动条颜色
    scrollbarHover: '#CECDCE',
    insertionMarker: '#000000',
    insertionMarkerOpacity: 0.2,
    fieldShadow: 'rgba(255, 255, 255, 1)',
    dragShadowOpacity: 0.6,
  },
  comments: false,
  collapse: false,
  sounds: false,
};

setProperty('--toolbox-selected-border', `${BLOCKS_DEFAULT_OPTIONS.colours.toolboxSelectedBorder}`);

// 生成唯一id
export const genUid = Blockly.utils.genUid

/**
 * Connect scratch blocks with the vm
 * @param {VirtualMachine} vm - The scratch vm
 * @return {Blockly} Blockly connected with the vm
 */
export default function (vm) {
  const controlColors = Object.assign({}, Blockly.Colours.control, {
    tertiary: '#ffffff',
    primary: '#244D6F',
    secondary: '#000000',
    colourStroke: '#000000',
  });

  const operatorsColors = Object.assign({}, Blockly.Colours.operators, {
    tertiary: '#ffffff',
    primary: '#FBC358',
    secondary: '#ffffff',
    colourStroke: '#ffffff'
  });

  const jsonForMenuBlock = function (name, menuOptionsFn, colors, start) {
    return {
      message0: '%1',
      args0: [
        {
          type: 'field_dropdown',
          name: name,
          options: function () {
            return start.concat(menuOptionsFn());
          },
        },
      ],
      inputsInline: true,
      output: 'String',
      colour: colors.primary,
      colourSecondary: colors.secondary,
      colourTertiary: colors.tertiary,
      outputShape: Blockly.OUTPUT_SHAPE_ROUND,
    };
  };

  const getSpriteMenu = function () {
    const spriteMenuItems = [];
    for (const targetId in vm.runtime.targets) {
      if (!Object.prototype.hasOwnProperty.call(vm.runtime.targets, 'targetId')) continue;
      if (vm.runtime.targets[targetId].isOriginal) {
        if (!vm.runtime.targets[targetId].isStage) {
          if (vm.runtime.targets[targetId] === vm.editingTarget) {
            continue;
          }
          spriteMenuItems.push([
            vm.runtime.targets[targetId].sprite.name,
            vm.runtime.targets[targetId].sprite.name,
          ]);
        }
      }
    }
    return spriteMenuItems;
  };

  // 对应的颜色对象 end
  Blockly.defineBlocksWithJsonArray = function (jsonArray) {
    for (var i = 0; i < jsonArray.length; i++) {
      var elem = jsonArray[i];
      if (!elem) {
        console.warn('Block definition #' + i + ' in JSON array is ' + elem + '. ' + 'Skipping.');
      } else {
        var typename = elem.type;
        if (typename == null || typename === '') {
          console.warn(
            'Block definition #' + i + ' in JSON array is missing a type attribute. Skipping.',
          );
        } else {
          //   if (Blockly.Blocks[typename]) {
          //     console.warn(
          //         'Block definition #' + i + ' in JSON array' +
          //         ' overwrites prior definition of "' + typename + '".');
          //   }
          Blockly.Blocks[typename] = {
            init: Blockly.jsonInitFactory_(elem),
          };
        }
      }
    }
  };

  // 循环次数
  Blockly.Blocks['control_loop'] = {
    init: function () {
      // 场景终止 init
      this.jsonInit({
        message0: '循环 %1 次',
        message1: '%1', // Statement
        args0: [
          {
            type: 'input_value',
            name: 'TIMES',
          },
        ],
        args1: [
          {
            type: 'input_statement',
            name: 'SUBSTACK',
          },
        ],
        category: Blockly.Categories.control,
        colour: controlColors.primary, // 背景颜色
        colourSecondary: controlColors.secondary,
        colourTertiary: controlColors.tertiary,
        extensions: ['shape_statement'],
      });
    },
  };

  Blockly.Blocks['control_loop_times'] = {
    init: function () {
      // 选择条件 menu init
      const min = 2;
      const max = 10;
      const conditions = [];

      for (let index = min; index <= max; index++) {
        const val = String(index);
        conditions.push([val, val]);
      }

      const json = jsonForMenuBlock('TIMES', getSpriteMenu, controlColors, conditions);
      this.jsonInit(json);
    },
  };

  // 退出条件
  Blockly.Blocks['control_exit'] = {
    init: function () {
      // 场景终止 init
      this.jsonInit({
        message0: '退出条件 %1',
        message1: '%1', // Statement
        args0: [
          {
            type: 'input_value',
            name: 'CONDITION',
            check: 'Boolean',
          },
        ],
        args1: [
          {
            type: 'input_statement',
            name: 'SUBSTACK',
          },
        ],
        category: Blockly.Categories.control,
        colour: controlColors.primary, // 背景颜色
        colourSecondary: controlColors.secondary,
        colourTertiary: controlColors.tertiary,
        extensions: ['shape_end'],
      });
    },
  };

  // 当
  Blockly.Blocks['control_when'] = {
    init: function () {
      // 当 init
      const json = {
        message0: '当 %1',
        args0: [
          {
            type: 'input_value',
            name: 'BOOLEAN',
            check: 'Boolean',
          }
        ],
        category: Blockly.Categories.control,
        colour: controlColors.primary, // 背景颜色
        colourSecondary: controlColors.secondary,
        colourTertiary: controlColors.tertiary,
        colourStroke: controlColors.colourStroke,
        extensions: ['shape_hat'],
      };
      this.jsonInit(json);
    },
  };

  // 前置条件
  Blockly.Blocks['control_pre_conditions'] = {
    init: function () {
      // 当 init
      const json = {
        message0: '前置条件 %1',
        args0: [
          {
            type: 'input_value',
            name: 'BOOLEAN',
            check: 'Boolean',
          }
        ],
        category: Blockly.Categories.control,
        colour: controlColors.primary, // 背景颜色
        colourSecondary: controlColors.secondary,
        colourTertiary: controlColors.tertiary,
        colourStroke: controlColors.colourStroke,
        extensions: ['shape_statement'],
      };
      this.jsonInit(json);
    },
  };

  Blockly.Blocks['control_if_else'] = {
    /**
     * Block for if-else.
     * @this Blockly.Block
     */
    init: function () {
      this.jsonInit({
        type: 'control_if_else',
        message0: "如果 %1 执行",
        message1: '%1',
        message2: Blockly.Msg.CONTROL_ELSE,
        message3: '%1',
        args0: [
          {
            type: 'input_value',
            name: 'CONDITION',
            check: 'Boolean',
          }
        ],
        args1: [
          {
            type: 'input_statement',
            name: 'SUBSTACK',
          }
        ],
        args3: [
          {
            type: 'input_statement',
            name: 'SUBSTACK2',
          }
        ],
        category: Blockly.Categories.control,
        colour: controlColors.primary, // 背景颜色
        colourSecondary: controlColors.secondary,
        colourTertiary: controlColors.tertiary,
        extensions: ['shape_statement'],
      });
    },
  };

  Blockly.Blocks['control_if'] = {
    /**
     * Block for if-then.
     * @this Blockly.Block
     */
    init: function () {
      this.jsonInit({
        type: 'control_if',
        message0: "如果 %1 执行",
        message1: '%1', // Statement
        args0: [
          {
            type: 'input_value',
            name: 'CONDITION',
            check: 'Boolean',
          }
        ],
        args1: [
          {
            type: 'input_statement',
            name: 'SUBSTACK',
          }
        ],
        category: Blockly.Categories.control,
        colour: controlColors.primary, // 背景颜色
        colourSecondary: controlColors.secondary,
        colourTertiary: controlColors.tertiary,
        extensions: ['shape_statement'],
      });
    },
  };

  // 与或非重写
  Blockly.Blocks.operator_or.init = function () {
    const json = {
      message0: Blockly.Msg.OPERATORS_OR,
      args0: [
        {
          type: 'input_value',
          name: 'OPERAND1',
          check: 'Boolean',
        },
        {
          type: 'input_value',
          name: 'OPERAND2',
          check: 'Boolean',
        },
      ],
      category: Blockly.Categories.operators,
      colour: operatorsColors.primary, // 背景颜色
      colourSecondary: operatorsColors.secondary,
      colourStroke: operatorsColors.colourStroke,
      colourTertiary: operatorsColors.tertiary,
      extensions: ['output_boolean'],
    };
    this.jsonInit(json);
  };

  Blockly.Blocks.operator_and.init = function () {
    const json = {
      message0: Blockly.Msg.OPERATORS_AND,
      args0: [
        {
          type: 'input_value',
          name: 'OPERAND1',
          check: 'Boolean',
        },
        {
          type: 'input_value',
          name: 'OPERAND2',
          check: 'Boolean',
        },
      ],
      category: Blockly.Categories.operators,
      colour: operatorsColors.primary, // 背景颜色
      colourSecondary: operatorsColors.secondary,
      colourTertiary: operatorsColors.tertiary,
      colourStroke: operatorsColors.colourStroke,
      extensions: ['output_boolean'],
    };
    this.jsonInit(json);
  };

  return Blockly;
}
